package top.jolyoulu.webcommon.filter;


import org.apache.catalina.util.ParameterMap;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;

/**
 * @Author: JolyouLu
 * @Date: 2023/1/21 16:17
 * @Description 构建可重复读取的Request
 */
public class MultiReadHttpServletRequestWrapper extends HttpServletRequestWrapper {

    //请求数据
    private String body;
    //请求二进制数据
    private byte[] bytes;
    //parameter数据
    private ParameterMap<String, String[]> params;

    public MultiReadHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        // 给参数集合赋值
        params = (ParameterMap) request.getParameterMap();
        if (request.getContentLength() > 0){
            try (ServletInputStream inputStream = request.getInputStream()){
                bytes = new byte[request.getContentLength()];
                inputStream.read(bytes);
                body = new String(bytes);
            }
        }else {
            bytes = new byte[]{};
            body = "";
        }
    }

    /**
     * 获取参数
     */
    @Override
    public String getParameter(String name) {
        String[] values = params.get(name);
        if (values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }

    /**
     * 获取参数Map
     * @return
     */
    @Override
    public Map<String, String[]> getParameterMap() {
        return params;
    }

    /**
     * 获取参数
     * @param name
     *            a <code>String</code> containing the name of the parameter
     *            whose value is requested
     * @return
     */
    @Override
    public String[] getParameterValues(String name) {
        String[] values = params.get(name);
        if (values == null || values.length == 0) {
            return null;
        }
        return values;
    }

    /**
     * 获取参数名
     * @return
     */
    @Override
    public Enumeration<String> getParameterNames() {
        return Collections.enumeration(params.keySet());
    }

    /**
     * 添加参数
     */
    public void addParameter(String name, Object value) {
        if (value != null) {
            params.setLocked(false);
            if (value instanceof String[]) {
                params.put(name, (String[]) value);
            } else if (value instanceof String) {
                params.put(name, new String[] { (String) value });
            } else {
                params.put(name, new String[] { String.valueOf(value) });
            }
            params.setLocked(true);
        }
    }

    /**
     * 删除参数
     */
    public void delParameter(String name) {
        params.setLocked(false);
        params.remove(name);
        params.setLocked(true);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        //这一步最关键
        //这一步使得后续获取InputStream都是这个对象
        //而在此时我们也把我们自定义的数据塞进去了
        //也就是说后续处理中获取到的参数就是我们此时塞进去的数据
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        ServletInputStream inputStream = new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            //这里流的读取，就是从我们自定义流中读取数据
            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
        return inputStream;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public byte[] getBytes() {
        return bytes;
    }

    public void setBytes(byte[] bytes) {
        this.bytes = bytes;
    }
}
